//
//  RHChangePasswordController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/20.
//

#import "RHChangePasswordController.h"
#import "RHCustomTimer.h"
#import "LCMD5Tool.h"

@interface RHChangePasswordController ()<UITextFieldDelegate>
@property(nonatomic, strong)QMUITextField *authTextField;
@property(nonatomic, strong)QMUITextField *NewPwdTextField;
@property(nonatomic, strong)QMUITextField *confirmPwdTextField;
@property(nonatomic ,strong) QMUIButton *sendBtn;
@property(nonatomic, strong)NSTimer *timer;
@property(nonatomic, assign)int second;
@end

@implementation RHChangePasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"修改密码".rh_localized];
    [self.view setBackgroundColor:CFTabViewBgColor];
    [self setupUI];

}
-(void)seccondReduce{
    self.second--;
    if(self.second ==0){
        [self.timer invalidate];
        self.title = nil;
        [self.sendBtn setTitle:@"获取验证码".rh_localized forState:UIControlStateNormal];
        [self.sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.sendBtn setBackgroundColor:CMainColorGreen];
        self.sendBtn.userInteractionEnabled = YES;
    }else{
        [self.sendBtn setTitle:[NSString stringWithFormat:@"%d",self.second] forState:UIControlStateNormal];
        [self.sendBtn setTitleColor:CMainColorGreen forState:UIControlStateNormal];
        [self.sendBtn setBackgroundColor:kCOLOR_HEX(@"E7E7E7")];
        self.sendBtn.userInteractionEnabled = NO;
        
    }
}

- (void)setupUI{
    
    UIView *bgView1 = [[UIView alloc] init];
    [bgView1 rounded:8 width:1 color:kBorderColor];
    [bgView1.layer setCornerRadius:8];
    [bgView1 setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:bgView1];
    
    QMUILabel *email_lab = [[QMUILabel alloc] init];
    [email_lab setTextAlignment:NSTextAlignmentLeft];
    [email_lab setFont:[UIFont systemFontOfSize:16]];
    [email_lab setTextColor:kCOLOR_HEX(@"3F4443")];
    [bgView1 addSubview:email_lab];
    
    UIView *bgView2 = [[UIView alloc] init];
    [bgView2 rounded:8 width:1 color:kBorderColor];
    [bgView2.layer setCornerRadius:8];
    [bgView2 setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:bgView2];
    
    QMUITextField *authTextField = [[QMUITextField alloc] init];
    [authTextField setTextAlignment:NSTextAlignmentLeft];
    [authTextField setFont:[UIFont systemFontOfSize:15]];
    [authTextField setTextColor:kCOLOR_HEX(@"3F4443")];
    [authTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [authTextField setPlaceholder:@"请输入验证码".rh_localized];
    authTextField.keyboardType = UIKeyboardTypeNumberPad;
    authTextField.delegate = self;
    authTextField.maximumTextLength = 6;
    [bgView2 addSubview:authTextField];
    self.authTextField = authTextField;
    
    QMUIButton *sendBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [sendBtn setBackgroundColor:CMainColorGreen];
    [sendBtn.layer setCornerRadius:8];
    sendBtn.titleLabel.numberOfLines = 0;
    sendBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    sendBtn.titleLabel.minimumScaleFactor = 0.5;
    sendBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [sendBtn setTitle:@"获取验证码".rh_localized forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:sendBtn];
    self.sendBtn = sendBtn;
    
    UIView *bgView3 = [[UIView alloc] init];
    [bgView3 rounded:8 width:1 color:kBorderColor];
    [bgView3.layer setCornerRadius:8];
    [bgView3 setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:bgView3];
    
    NSArray *titles = @[@"请输入新密码".rh_localized,@"再次输入新密码".rh_localized];
    NSMutableArray *textFields = [NSMutableArray array];
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUITextField *textField = [[QMUITextField alloc] init];
        [textField setTextAlignment:NSTextAlignmentLeft];
        [textField setFont:[UIFont systemFontOfSize:15]];
        [textField setClearButtonMode:UITextFieldViewModeWhileEditing];
        [textField setPlaceholder:obj];
        [textField setTextColor:kCOLOR_HEX(@"3F4443")];
        [bgView3 addSubview:textField];
        [textFields addObject:textField];
        if(idx==0){
            _NewPwdTextField = textField;
        }else{
            _confirmPwdTextField = textField;
        }
        textField.maximumTextLength = 16;
        textField.keyboardType = UIKeyboardTypeASCIICapable;
        textField.clearButtonMode = UITextFieldViewModeNever;
        textField.secureTextEntry = YES;
        QMUIButton *showPwdBtn = [[QMUIButton alloc]init];
        [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd"] forState:UIControlStateNormal];
        [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd_s"] forState:UIControlStateSelected];
        [bgView3 addSubview:showPwdBtn];
        [showPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(35);
            make.right.equalTo(textField).offset(-5);
            make.centerY.equalTo(textField);
        }];
        
        [[showPwdBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIButton * _Nullable x) {
            x.selected = !x.selected;
            textField.secureTextEntry = !x.selected;
        }];
    }];
     
    [textFields mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
    }];

    [textFields mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:30 leadSpacing:15 tailSpacing:15];
    
    UIView *lineV = [[UIView alloc] init];
    [lineV setBackgroundColor:CFCellLineColor];
    [bgView3 addSubview:lineV];
    
    QMUIButton *confirmBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [confirmBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [confirmBtn.layer setCornerRadius:8];
    [confirmBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:confirmBtn];
    
    [bgView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-30, 50));
        make.top.mas_offset(15);
        make.centerX.mas_offset(0);
    }];
    
    
    [bgView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-130, 50));
        make.top.mas_equalTo(bgView1.mas_bottom).offset(10);
        make.left.mas_offset(15);
    }];
    
    [bgView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-30, 120));
        make.top.mas_equalTo(bgView2.mas_bottom).offset(10);
        make.centerX.mas_offset(0);
    }];
    
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(1);
        make.centerY.mas_offset(0);
    }];
    
    [email_lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 15, 5, 15));
    }];
    
    [authTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 15, 5, 15));
    }];
    
    CGFloat width = [sendBtn.titleLabel.text getStringWidthFont:sendBtn.titleLabel.font limitHeight:20];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView2.mas_right).offset(10);
        make.top.bottom.equalTo(bgView2);
        make.right.mas_offset(-15);
        make.width.offset(width+15);
    }];
    
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    
    [email_lab setText:[PrivateMange share].currentUser.email];
    
    kWeakSelf;
#pragma mark ------   验证码
    [[sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSDictionary *para = @{@"sendEmail":[PrivateMange share].currentUser.email,
                               @"action":@"修改密码,获取验证码"};
        [QMUITips showLoading:@"获取验证码...".rh_localized inView:weakSelf.view];
        [BaseModel startWithCompletionAPIKey:H_sendCode header:@{@"brandId":brand_id} argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"成功".rh_localized];
                weakSelf.second = 60;
                weakSelf.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(seccondReduce) userInfo:nil repeats:YES];
                [[NSRunLoop currentRunLoop]addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        }];
    }];
    
#pragma mark ------   修改密码
    [[confirmBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(weakSelf.authTextField.text.length==0){
            [QMUITips showError:@"请输入验证码".rh_localized];
            return;
        }
        
        if(![NSString validatePassword:weakSelf.NewPwdTextField.text]){
            [QMUITips showError:@"密码长度为8 ~ 16，必须包含大写字母、小写字母和数字".rh_localized];
            return;
        }
        
        if(![weakSelf.NewPwdTextField.text isEqualToString:weakSelf.confirmPwdTextField.text]){
            [QMUITips showError:@"两次输入的密码不一致".rh_localized];
            return;
        }
        
        NSDictionary *para = @{@"email":[PrivateMange share].currentUser.email,
                               @"newPassword":[LCMD5Tool md5HexDigest:weakSelf.NewPwdTextField.text],
                               @"recode":weakSelf.authTextField.text
        };
        [BaseModel startWithCompletionAPIKey:H_changePassword argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"成功".rh_localized];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
    }];
    
}


@end
